import { Reducer, Effect } from 'umi';
import { getMethod } from '@/services/demo';
import Counsellor from '@/pages/Counsellor';
import {
  getMessageList,
  getDetialList,
  getStudentListforGroup,
  setGroupByGroup,
  getOptions,
  getNoticeDetail,
  deleteList,
  getStudentRegister,
  setFeedBack,
  getStuBaseInfo,
  getStuFamilyInfo
} from '@/services/Counsellor';
import { setNewMessage, takePartIn } from '@/services/fileService'
import { Upload, message } from 'antd';
//import { Reducer } from 'redux';
// import { Effect } from 'dva';
/*
-----------------------------------------------------------------------------------------------------------------
本model用来演示正规的流程，即
①组件连接仓库；
②组件通过connect连接后给组件自动传的参数dispatch访问仓库中的异步函数effects；
③effects获取到数据后调用同步函数reducers存储数据到仓库state中
④组件自动更新参数并重新渲染
-----------------------------------------------------------------------------------------------------------------
 */


/*
-----------------------------------------------------------------------------------------------------------------
ts规范：对变量进行声明
 */
//对state声明，state用于仓库存储数据，也就是说state就是仓库
export type StateType = {
  list?: any[];
};
//对model声明
export type ExampleModelType = {
  namespace: string;
  state: StateType;
  effects: {
    getMessageListEffects: Effect;//获取通知列表
    getDetialListEffects: Effect;//获取通知详情列表
    setNewMessageEffects: Effect;//新建通知
    getStudentListforGroupEffects: Effect;//预览分组列表
    setGroupByGroupEffects: Effect;//按照分组建立分群
    getOptionsEffects: Effect;//获取辅导员选项列表
    getNoticeDetailEffects: Effect;//获取通知内容
    deleteListEffects: Effect;//删除通知
    getStudentRegisterEffects: Effect;//获取学生报到和缴费信息
    setFeedBackEffects: Effect;//学生设置活动反馈
    takePartInEffects: Effect;//学生报名参加活动
    getStuBaseInfoEffects: Effect;//辅导员获取学生基本信息
    getStuFamilyInfoEffects: Effect;//辅导员获取学生家庭信息
  };
  reducers: {
    getListReducers: Reducer<StateType>;
  };
};
/*
ts规范：对变量进行声明
-----------------------------------------------------------------------------------------------------------------
 */

/*
-----------------------------------------------------------------------------------------------------------------
model结构：namespace，state（仓库，用来存储数据），
effects异步处理，reducers同步操作（用于接收effects的结果并存到state中），subscription订阅（用于监听页面的跳转）
state变化后，连接此model的组件所接收到的参数会自动渲染
 */
export type Status = {
  color: string;
  text: string;
};
const Model_Counsellor: ExampleModelType = {
  //本model唯一标识，命名标准：不能有'-'，可以有'_'，可以有大写
  //个人标准：以后都以'Model_'开头
  namespace: 'Model_Counsellor',//Model_ExampleModel里面存的是state
  state: {
    list: [],
  },
  //命名规范（个人）：函数功能+FromServices+Effects
  effects: {
    * getMessageListEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红
      const result: any = yield call(getMessageList, '', payload.value);
      let list = [
        {
          'id': 1,
          'title': '班会',
          'receiverCount': 5,
          'readCount': 3,
          'createTime': '2023-07-19'
        }
      ]
      // yield put({
      //     type: 'getListReducers',
      //     payload: list
      const transformedData = result.result.map(
        (item: any, key: number) => ({
          ...item,
          key: key + 1, // 从 1 开始递增
        }),
      );
      payload.callback(transformedData)
    },
    * getDetialListEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红
      const result: any = yield call(getDetialList, '', payload.value);
      // yield put({
      //     type: 'getListReducers',
      //     payload: list
      const transformedData = result.result.map(
        (item: any, key: number) => ({
          ...item,
          key: key + 1, // 从 1 开始递增
        }),
      );
      payload.callback(transformedData)
    },
    * getStuBaseInfoEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红
      const result: any = yield call(getStuBaseInfo, '', payload.stuCode);
      let list =
      {
        "code": "200",
        "message": "成功!",
        "result": {
          "stuName": "黄天博",
          "stuCode": "185874",
          "gender": "0",
          "ethnicity": "汉族",
          "birth": "10010101",
          "politicalParty": "党员",
          "hometown": "河北省沧州市",
          "idCard": "234346哇73547",
          "phoneNumber": "17320040765",
          "email": "12121@qq.com",
          "originPlace": "河北",
          "collegeEntranceScore": 666,
          "classLabel": "电气1111",
          "instructorName": "初艳飞",
          "instructorNumber": "18722434200",
          "classAdvisor": "招福如",
          "advisorNumber": "123124155",
          "dormitoryCampus": "北辰校区",
          "dormitoryBuilding": "东2",
          "dormitoryRoom": "222",
          "hobbies": "好好学习",
          "advantages": "抽烫嫖赌",
          "isReported": "1"
        }
      }


      if (result.code == "200") {
        payload.callback(result.result)
      }
      else message.error("获取学生信息失败")
    },
    * getStuFamilyInfoEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红
      const result: any = yield call(getStuFamilyInfo, '', payload.stuCode);
      let list =
      {
        "code": "200",
        "message": "成功!",
        "result": {
          "homeAddress": "河北省东北市",
          "isFinanciallyChallenged": "0",
          "isScholarshipApplied": "0",
          "familyMemberInfos": [
            {
              "parentName": "黄天化",
              "parentRelation": "0",
              "parentNumber": "13465232231"
            },
            {
              "parentName": "黄天虎",
              "parentRelation": "2",
              "parentNumber": "15351341324"
            }
          ]
        }
      }
      if (result.code == "200") {
        payload.callback(result.result)
      }
      else message.error("获取学生家庭信息失败")
    },
    * getStudentListforGroupEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红、
      //console.log(payload.data)
      const result: any = yield call(getStudentListforGroup, '', payload.data);
      let list = [
        {
          'stuName': '黄天博',
          'stuCode': localStorage.getItem('userAccount'),
          'majorLabel': '电气工程及其自动化',
          'classLabel': '电气1122',
          'phoneNumber': '231'
        },
        {
          'stuName': '佘甲帅',
          'stuCode': '185875',
          'majorLabel': '电气工程及其自动化',
          'classLabel': '电气1122',
          'phoneNumber': '356346'
        },
        {
          'stuName': '陈晓冲',
          'stuCode': '185876',
          'majorLabel': '电气工程及其自动化',
          'classLabel': '电气1122',
          'phoneNumber': '45354345'
        },
        {
          'stuName': '郑海飞',
          'stuCode': '185877',
          'majorLabel': '新能源',
          'classLabel': '新能1111',
          'phoneNumber': '1345145'
        },
        {
          'stuName': '吴金广',
          'stuCode': '185878',
          'majorLabel': '新能源',
          'classLabel': '新能1111',
          'phoneNumber': '1451345'
        }
      ]
      // yield put({
      //     type: 'getListReducers',
      //     payload: list
      // });
      const transformedData = result.result.map(
        (item: any, key: number) => ({
          ...item,
          key: key + 1, // 从 1 开始递增
        }),
      );
      payload.callback(transformedData)
    },
    * setNewMessageEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红
      console.log(payload)
      let newMessage
      if (payload.value.upload) {
        let messageList = {
          title: payload.value.messageName,
          content: payload.content,
          teacherCode: payload.teacherCode,
          clusterType: payload.value.number,
          label: payload.value.label,
          isFile: payload.value.isFile,
          form: {},
          upload: payload.value.upload[0]
        }
        if (payload.value.selfSelect) {
          if (payload.value.selfSelect == '1') {
            messageList.form = {
              type: payload.value.selfSelect,
              title: payload.value.name,
              option: payload.value.option,
            };
          } else if (payload.value.selfSelect == '0') {
            messageList.form = {
              type: payload.value.selfSelect,
              title: payload.value.name,
            };
          }
        }
        newMessage = messageList
      } else {
        let messageList2 = {
          title: payload.value.messageName,
          content: payload.content,
          teacherCode: payload.teacherCode,
          clusterType: payload.value.number,
          label: payload.value.label,
          isFile: payload.value.isFile,
          form: {}
        }
        if (payload.value.selfSelect) {
          if (payload.value.selfSelect == '1') {
            messageList2.form = {
              type: payload.value.selfSelect,
              title: payload.value.name,
              option: payload.value.option,
            };
          } else if (payload.value.selfSelect == '0') {
            messageList2.form = {
              type: payload.value.selfSelect,
              title: payload.value.name,
            };
          }
        }
        newMessage = messageList2
      }
      console.log(newMessage)
      const result: any = yield call(setNewMessage, '', newMessage);
      if (result.code == '200') {
        message.success(result.message)
        window.location.reload()
      } else {
        message.error('新建通知出错')
      }
    },
    * setGroupByGroupEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红
      const result: any = yield call(setGroupByGroup, '', payload);
      if (result.code == '200') {
        message.success(result.message)
      } else {
        message.error('新建分群出错')
      }
    },
    * setFeedBackEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红
      const result: any = yield call(setFeedBack, '', payload);
      if (result.code == '200') {
        message.success(result.message)
      } else {
        message.error('活动反馈出错')
      }
    },
    * takePartInEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红
      const result: any = yield call(takePartIn, '', payload);
      if (result.code == '200') {
        message.success(result.message)
        window.location.reload()
      } else if (result.code == null) {
        message.error(result.message + ',请勿重复报名')
      }
      else {
        message.error('活动报名出错')
      }
    },
    * getOptionsEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红
      const result: any = yield call(getOptions, '',);
      payload.callback(result.result)
    },
    * getNoticeDetailEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红
      console.log(payload.id)
      const result: any = yield call(getNoticeDetail, '', payload.id);
      console.log(result)
      payload.callback(result.result)
    },
    * getStudentRegisterEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红
      console.log(payload.id)
      const result: any = yield call(getStudentRegister, '', payload.id);
      console.log(result.result)
      payload.callback(result.result)
    },
    * deleteListEffects({ payload }: any, {
      call,
      put
    }: any): Generator {//: Generator解决yield报红
      console.log(payload.id)
      const result: any = yield call(deleteList, '', payload.id);
      console.log(result)
      if (result.code == "200") {
        payload.callback(result.result)
      }
      else message.error("删除失败")
    },
  },
  //命名规范（个人）：函数功能+Reducers
  reducers: {
    getListReducers(state, { payload }) {
      //返回形式return {...state}，必须是"...state"，否则报错
      console.log(state)
      return {
        ...state,
        list: payload
      };//将payload赋值给list
    },
  }
};
/*
model结构
-----------------------------------------------------------------------------------------------------------------
 */


export default Model_Counsellor;
